package com.xyht.sca_s.student_manage_system.modules.attendance.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.DynamicSchedulingTaskUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.SmsAttendance;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.SmsAttendanceDetail;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.SmsAttendanceEvent;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.req.SmsAttendanceReq;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.resp.SmsAttendanceAllDetailResp;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.resp.SmsAttendanceDetailResp;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.resp.SmsAttendanceResp;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.resp.UserInfoAndStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.attendance.mapper.SmsAttendanceDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.attendance.mapper.SmsAttendanceEventMapper;
import com.xyht.sca_s.student_manage_system.modules.attendance.mapper.SmsAttendanceMapper;
import com.xyht.sca_s.student_manage_system.modules.attendance.service.SmsAttendanceDetailService;
import com.xyht.sca_s.student_manage_system.modules.attendance.service.SmsAttendanceService;
import com.xyht.sca_s.student_manage_system.modules.attendance.util.CheckOutlierUtil;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.AppTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.RangeTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.util.NewTipsUtil;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.tips.utils.TipsUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.constant.SchedulingTaskTypeConstant.SCHEDULING_TASK_ATTENDANCE;
import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.attendance.constant.AttendanceStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.attendance.constant.AttendanceTaskStatusConstant.ATTENDANCE_TASK_STATUS_CLOSE;
import static com.xyht.sca_s.student_manage_system.modules.attendance.constant.AttendanceTaskStatusConstant.ATTENDANCE_TASK_STATUS_OPEN;
import static com.xyht.sca_s.student_manage_system.modules.attendance.constant.CommonConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.OrgTypeConstant.ORG_TYPE_CLASS;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.TeacherAndStudentFlag.STUDENT_FLAG;


/**
 * <p>
 * 考勤打卡 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-02-23
 */
@Service
public class SmsAttendanceServiceImpl extends ServiceImpl<SmsAttendanceMapper, SmsAttendance> implements SmsAttendanceService {
    @Autowired
    private SmsAttendanceMapper smsAttendanceMapper;
    @Autowired
    private SmsAttendanceDetailMapper smsAttendanceDetailMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Autowired
    private SmsAttendanceEventMapper smsAttendanceEventMapper;
    @Autowired
    private SmsOrgUserRelationMapper smsOrgUserRelationMapper;
    @Autowired
    private SmsAttendanceDetailService smsAttendanceDetailService;
    @Autowired
    private DynamicSchedulingTaskUtil dynamicSchedulingTaskUtil;
    @Autowired
    private CheckOutlierUtil checkOutlierUtil;
    @Autowired
    private SmsUserStudentRelationMapper smsUserStudentRelationMapper;
    @Autowired
    private TipsUtil tipsUtil;
    @Autowired
    private NewTipsUtil newTipsUtil;


    @Override
    @Transactional
    public ResponseResult createAttendance(SmsAttendanceReq smsAttendanceReq, String user_id) {
        if (isNullOrEmpty(smsAttendanceReq.getAttendanceName()) || isNullOrEmpty(smsAttendanceReq.getAttendanceTime())
                || isNullOrEmpty(smsAttendanceReq.getAttendanceEvent())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (isNullOrEmpty(smsAttendanceReq.getAttendanceOrg()) || smsAttendanceReq.getAttendanceOrg().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (smsAttendanceReq.getAttendanceTime() < ATTENDANCE_TIME_MIN || smsAttendanceReq.getAttendanceTime() > ATTENDANCE_TIME_MAX) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        List<SmsAttendance> attendanceList = smsAttendanceMapper.selectList(new QueryWrapper<SmsAttendance>()
                .lambda()
                .eq(SmsAttendance::getAttendanceUserId, user_id)
                .ge(SmsAttendance::getEndTime, new Date()));
        if (attendanceList != null && attendanceList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_CREATE_TASK_LIMIT);
        }

        int total_num = 0;
        for (String orgID : smsAttendanceReq.getAttendanceOrg()) {
            SmsOrgStructure orgStructure = smsOrgStructureMapper.selectById(orgID);
            if (orgStructure == null || orgStructure.getId() == null) {
                return CommonResult.failed(CommonCodeEnum.ATTENDANCE_ORG_CLASS_NOT_EXIST);
            }
            if (!orgStructure.getLevel().equals(ORG_TYPE_CLASS + "")) {
                return CommonResult.failed(CommonCodeEnum.ATTENDANCE_ORG_NOT_CLASS);
            }

            List<String> userIDList = smsOrgUserRelationMapper.selectList(new QueryWrapper<SmsOrgUserRelation>()
                    .lambda()
                    .eq(SmsOrgUserRelation::getOrgId, orgID))
                    .stream()
                    .map(SmsOrgUserRelation::getUserId)
                    .collect(Collectors.toList());
            if (userIDList.size() > 0) {
                //班级人数统计
                Integer count = smsUserMapper.selectCount(new QueryWrapper<SmsUser>()
                        .lambda()
                        .in(SmsUser::getId, userIDList)
                        .eq(SmsUser::getFlag, STUDENT_FLAG));
                total_num = total_num + count;
            }
        }
        if (total_num < ATTENDANCE_MIN_STUDENT_NUM) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_CLASS_NUM_NOT_ENOUGH);
        }

        SmsUser smsUser = smsUserMapper.selectById(user_id);

        SmsAttendance smsAttendance = new SmsAttendance();
        BeanUtils.copyProperties(smsAttendanceReq, smsAttendance);

        smsAttendance.setAttendanceUserId(user_id);
        smsAttendance.setAttendanceUsername(smsUser.getRealName());
        smsAttendance.setAttendanceOrg(JSONObject.toJSONString(smsAttendanceReq.getAttendanceOrg()));
        Date nowDate = new Date();
        smsAttendance.setCreateTime(nowDate);
        smsAttendance.setTotalNum(total_num);
        smsAttendance.setEndTime(TimeUtil.AddMinute(nowDate, smsAttendanceReq.getAttendanceTime()));

        smsAttendanceMapper.insert(smsAttendance);

        for (String orgID : smsAttendanceReq.getAttendanceOrg()) {
            List<String> userIDList = smsOrgUserRelationMapper.selectList(new QueryWrapper<SmsOrgUserRelation>()
                    .lambda()
                    .eq(SmsOrgUserRelation::getOrgId, orgID))
                    .stream()
                    .map(SmsOrgUserRelation::getUserId)
                    .collect(Collectors.toList());
            if (userIDList.size() > 0) {
                //班级学生添加
                List<SmsAttendanceDetail> attendanceDetailList = new ArrayList<>();
                List<UserInfoAndStudentInfoResp> userList = smsUserStudentRelationMapper
                        .selectJoinList(UserInfoAndStudentInfoResp.class,new MPJLambdaWrapper<SmsUserStudentRelation>()
                        .selectAll(SmsUserStudentRelation.class)
                        .selectAll(SmsUser.class)
                        .selectAll(SmsStudentInfo.class)
                        .selectAs(SmsUser::getId,UserInfoAndStudentInfoResp::getUserId)
                        .selectAs(SmsStudentInfo::getId,UserInfoAndStudentInfoResp::getStuId)
                        .leftJoin(SmsUser.class,SmsUser::getId,SmsUserStudentRelation::getUserId)
                        .leftJoin(SmsStudentInfo.class,SmsStudentInfo::getId,SmsUserStudentRelation::getStuId)
                        .in(SmsUserStudentRelation::getUserId,userIDList)
                        .eq(SmsUser::getFlag, STUDENT_FLAG)
                        )
                        ;
                if (userList.size() < 1) {
                    continue;
                }
                for (UserInfoAndStudentInfoResp user : userList) {
                    SmsAttendanceDetail smsAttendanceDetail = new SmsAttendanceDetail();
                    smsAttendanceDetail.setAttendanceId(smsAttendance.getId());
                    smsAttendanceDetail.setStuId(user.getUserId());
                    smsAttendanceDetail.setStuName(user.getRealName());
                    smsAttendanceDetail.setAttendanceStatus(ATTENDANCE_STATUS_DOING);
                    smsAttendanceDetail.setStuPic(user.getUserPic());
                    smsAttendanceDetail.setStuCollege(user.getStuCollege());
                    smsAttendanceDetail.setStuMajor(user.getStuMajor());
                    smsAttendanceDetail.setStuGrade(user.getStuGrade());
                    smsAttendanceDetail.setStuClass(user.getStuClass());
                    attendanceDetailList.add(smsAttendanceDetail);
                }
                smsAttendanceDetailService.saveBatch(attendanceDetailList);
            }
        }

        SmsAttendanceEvent attendanceEvent = new SmsAttendanceEvent();
        attendanceEvent.setAttendanceId(smsAttendance.getId());
        attendanceEvent.setAttendanceUser(user_id);
        attendanceEvent.setEventName(smsAttendanceReq.getAttendanceEvent());
        smsAttendanceEventMapper.insert(attendanceEvent);

        //添加定时任务
        ResponseResult result = dynamicSchedulingTaskUtil.createTask(smsAttendance.getId(),
                SCHEDULING_TASK_ATTENDANCE,
                TimeUtil.AddMinute(nowDate, smsAttendanceReq.getAttendanceTime()));
        if (!result.getSuccess()) {
            ExceptionCast.cast(result);
        }

        //添加消息待办
        newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_DEAL,
                user_id,
                RangeTypeEnum.RANGE_TYPE_ENUM_ORG,
                smsAttendanceReq.getAttendanceOrg(),
                AppTypeEnum.APP_TYPE_ENUM_ATTENDANCE,
                smsAttendance.getId(),
                null);
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult updateAttendance(SmsAttendanceReq smsAttendanceReq, String user_id) {
        if (isNullOrEmpty(smsAttendanceReq.getId()) || isNullOrEmpty(smsAttendanceReq.getAttendanceName())
                || isNullOrEmpty(smsAttendanceReq.getAttendanceEvent())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsAttendance queryAttendance = smsAttendanceMapper.selectById(smsAttendanceReq.getId());
        if (queryAttendance == null || queryAttendance.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_NOT_EXIST);
        }

        if (!queryAttendance.getAttendanceUserId().equals(user_id)) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_UPDATE_DENY);
        }

        SmsAttendance smsAttendance = new SmsAttendance();
        smsAttendance.setId(smsAttendanceReq.getId());
        smsAttendance.setAttendanceName(smsAttendanceReq.getAttendanceName());
        smsAttendanceMapper.updateById(smsAttendance);

        smsAttendanceEventMapper.delete(new QueryWrapper<SmsAttendanceEvent>()
                .lambda()
                .eq(SmsAttendanceEvent::getAttendanceId, smsAttendanceReq.getId()));

        SmsAttendanceEvent attendanceEvent = new SmsAttendanceEvent();
        attendanceEvent.setAttendanceId(smsAttendanceReq.getId());
        attendanceEvent.setAttendanceUser(user_id);
        attendanceEvent.setEventName(smsAttendanceReq.getAttendanceEvent());
        smsAttendanceEventMapper.insert(attendanceEvent);

        return CommonResult.success();
    }

    @Override
    public ResponseResult closeAttendance(SmsAttendanceReq smsAttendanceReq,String user_id) {
        if (isNullOrEmpty(smsAttendanceReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsAttendance queryAttendance = smsAttendanceMapper.selectOne(new QueryWrapper<SmsAttendance>()
                .lambda()
                .eq(SmsAttendance::getId, smsAttendanceReq.getId())
                .eq(SmsAttendance::getAttendanceUserId, user_id));
        if (queryAttendance == null || queryAttendance.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_NOT_EXIST);
        }

        long nowTime = new Date().getTime();
        long endTime = queryAttendance.getEndTime().getTime();
        if (nowTime - endTime >= 0) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_CLOSE_ALREADY);
        }

        SmsAttendance smsAttendance = new SmsAttendance();
        smsAttendance.setId(smsAttendanceReq.getId());
        smsAttendance.setEndTime(new Date());
        smsAttendanceMapper.updateById(smsAttendance);

        //关闭定时任务
        dynamicSchedulingTaskUtil.cancelTask(smsAttendanceReq.getId());

        checkOutlierUtil.checkOutlier(smsAttendanceReq.getId());

        //通知关闭
        newTipsUtil.cancelFinishTips(smsAttendanceReq.getId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult getHistoryAttendanceEvent(String search_str,String user_id) {
        QueryWrapper<SmsAttendanceEvent> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(search_str)){
            queryWrapper.lambda().like(SmsAttendanceEvent::getEventName,search_str);
        }
        queryWrapper.select("DISTINCT event_name").lambda().eq(SmsAttendanceEvent::getAttendanceUser, user_id);
        List<String> eventList = smsAttendanceEventMapper.selectList(queryWrapper)
                .stream()
                .map(SmsAttendanceEvent::getEventName)
                .collect(Collectors.toList());
        return CommonResult.success(eventList);
    }

    @Override
    public ResponseResult getAttendanceDetail(String attendance_id, String user_id) {
        if (isNullOrEmpty(attendance_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsAttendance queryAttendance = smsAttendanceMapper.selectById(attendance_id);
        if (queryAttendance == null || queryAttendance.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_NOT_EXIST);
        }

        SmsAttendanceAllDetailResp smsAttendanceResp = new SmsAttendanceAllDetailResp();
        BeanUtils.copyProperties(queryAttendance, smsAttendanceResp);

        //考勤事件获取
        SmsAttendanceEvent smsAttendanceEvent = smsAttendanceEventMapper.selectOne(new QueryWrapper<SmsAttendanceEvent>()
                .lambda()
                .eq(SmsAttendanceEvent::getAttendanceId, attendance_id));
        if (smsAttendanceEvent!=null && smsAttendanceEvent.getId() != null){
            smsAttendanceResp.setAttendanceEven(smsAttendanceEvent.getEventName());
        }

        //考勤任务状态 剩余考勤时间
        int attendanceStatus;
        int statusTime;
        Date nowDate = new Date();
        long nowTime = nowDate.getTime();
        long endTime = queryAttendance.getEndTime().getTime();
        long leaveTime = endTime - nowTime;
        if (leaveTime <= 0) {
            attendanceStatus = ATTENDANCE_TASK_STATUS_CLOSE;
            statusTime = 0;
        } else {
            attendanceStatus = ATTENDANCE_TASK_STATUS_OPEN;
            statusTime = Math.round((float) leaveTime / 1000);
        }
        smsAttendanceResp.setStatus(attendanceStatus);
        smsAttendanceResp.setStatusTime(statusTime);

        //考勤人数
        Integer actualNum = smsAttendanceDetailMapper.selectCount(new QueryWrapper<SmsAttendanceDetail>()
                .lambda()
                .eq(SmsAttendanceDetail::getAttendanceId, queryAttendance.getId())
                .and(smsStudentInfoLambdaQueryWrapper ->
                        smsStudentInfoLambdaQueryWrapper
                                .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_NORMAL)
                                .or()
                                .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_TAB_NORMAL)
                                .or()
                                .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_SIGN_IN_CHECKING)));
        smsAttendanceResp.setActualNum(actualNum);

        //考勤班级组织
        List<String> attendanceOrg = JSONObject.parseArray(smsAttendanceResp.getAttendanceOrg(), String.class);
        List<String> attendanceOrgName = new ArrayList<>();
        if (attendanceOrg != null && attendanceOrg.size() > 0) {
            attendanceOrgName = attendanceOrg.stream().map(org -> {
                SmsOrgStructure orgStructure = smsOrgStructureMapper.selectById(org);
                return orgStructure.getOrgName();
            }).collect(Collectors.toList());
        }
        smsAttendanceResp.setAttendanceOrg(JSONObject.toJSONString(attendanceOrgName));

        //考勤学生详情
        List<SmsAttendanceDetailResp> detailRespList = smsAttendanceDetailMapper.selectList(new QueryWrapper<SmsAttendanceDetail>()
                .lambda()
                .eq(SmsAttendanceDetail::getAttendanceId, queryAttendance.getId()))
                .stream()
                .map(attendanceDetail -> {
                    SmsAttendanceDetailResp attendanceDetailResp = new SmsAttendanceDetailResp();
                    BeanUtils.copyProperties(attendanceDetail, attendanceDetailResp);
                    return attendanceDetailResp;
                })
                .collect(Collectors.toList());
        smsAttendanceResp.setStudentList(detailRespList);
        return CommonResult.success(smsAttendanceResp);
    }

    @Override
    public ResponseResult getAttendanceList(Integer pageNum, Integer pageSize, String bg_date, String end_date,
                                            String user_id, String event_name, Integer status, String search_str) {
        Date bgDate = null;
        Date endDate = null;
        if (!isNullOrEmpty(bg_date)) {
            bgDate = TimeUtil.StringtoDate(bg_date);
        }
        if (!isNullOrEmpty(end_date)) {
            endDate = TimeUtil.StringtoDate(end_date);
        }

        Page<SmsAttendance> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsAttendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SmsAttendance::getAttendanceUserId, user_id)
                .orderByDesc(SmsAttendance::getCreateTime);
        if (bgDate != null) {
            queryWrapper.lambda().ge(SmsAttendance::getCreateTime, bgDate);
        }
        if (endDate != null) {
            queryWrapper.lambda().le(SmsAttendance::getCreateTime, endDate);
        }
        if (status != null) {
            if (status == ATTENDANCE_TASK_STATUS_OPEN) {
                queryWrapper.lambda().lt(SmsAttendance::getEndTime, new Date());
            } else if (status == ATTENDANCE_TASK_STATUS_CLOSE) {
                queryWrapper.lambda().ge(SmsAttendance::getEndTime, new Date());
            }
        }
        if (!isNullOrEmpty(search_str)) {
            queryWrapper.lambda().eq(SmsAttendance::getAttendanceName, search_str);
        }
        smsAttendanceMapper.selectPage(page, queryWrapper);
        List<SmsAttendanceResp> respList = page.getRecords().stream().map(smsAttendance -> {
            SmsAttendanceResp smsAttendanceResp = new SmsAttendanceResp();
            BeanUtils.copyProperties(smsAttendance, smsAttendanceResp);

            //考勤任务状态 剩余考勤时间
            int attendanceStatus;
            int statusTime = 0;
            Date nowDate = new Date();
            long nowTime = nowDate.getTime();
            long endTime = smsAttendance.getEndTime().getTime();
            long leaveTime = endTime - nowTime;
            if (leaveTime >= 0) {
//                attendanceStatus = ATTENDANCE_TASK_STATUS_CLOSE;
//                statusTime = 0;
//            } else {
//                attendanceStatus = ATTENDANCE_TASK_STATUS_OPEN;
                statusTime = Math.round((float) leaveTime / 1000);
            }
//            smsAttendanceResp.setStatus(attendanceStatus);
            smsAttendanceResp.setStatusTime(statusTime);

            //考勤人数
            Integer actualNum = smsAttendanceDetailMapper.selectCount(new QueryWrapper<SmsAttendanceDetail>()
                    .lambda()
                    .eq(SmsAttendanceDetail::getAttendanceId, smsAttendance.getId())
                    .and(smsStudentInfoLambdaQueryWrapper ->
                            smsStudentInfoLambdaQueryWrapper
                                    .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_NORMAL)
                                    .or()
                                    .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_TAB_NORMAL)
                                    .or()
                                    .eq(SmsAttendanceDetail::getAttendanceStatus, ATTENDANCE_STATUS_SIGN_IN_CHECKING)));
            smsAttendanceResp.setActualNum(actualNum);

            //考勤班级组织
            List<String> attendanceOrg = JSONObject.parseArray(smsAttendanceResp.getAttendanceOrg(), String.class);
            List<String> attendanceOrgName = new ArrayList<>();
            if (attendanceOrg != null && attendanceOrg.size() > 0) {
                attendanceOrgName = attendanceOrg.stream().map(org -> {
                    SmsOrgStructure orgStructure = smsOrgStructureMapper.selectById(org);
                    return orgStructure.getOrgName();
                }).collect(Collectors.toList());
            }
            smsAttendanceResp.setAttendanceOrg(JSONObject.toJSONString(attendanceOrgName));
            return smsAttendanceResp;
        }).collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(respList, total);
    }

    @Override
    public ResponseResult checkOutlierStudent(SmsAttendanceReq smsAttendanceReq, String user_id) {
        if (isNullOrEmpty(smsAttendanceReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsAttendance queryAttendance = smsAttendanceMapper.selectOne(new QueryWrapper<SmsAttendance>()
                .lambda()
                .eq(SmsAttendance::getId, smsAttendanceReq.getId())
                .eq(SmsAttendance::getAttendanceUserId, user_id));
        if (queryAttendance == null || queryAttendance.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_NOT_EXIST);
        }

        List<SmsAttendanceDetail> positionList = smsAttendanceDetailMapper.selectList(new QueryWrapper<SmsAttendanceDetail>()
                .lambda()
                .isNotNull(SmsAttendanceDetail::getLongitude));
        if (positionList == null || positionList.size() < ATTENDANCE_MIN_STUDENT_NUM) {
            return CommonResult.failed(CommonCodeEnum.ATTENDANCE_SIGN_IN_NUM_NOT_ENOUGH);
        }
        //坐标离散检测
        checkOutlierUtil.checkOutlier(smsAttendanceReq.getId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult addAttendanceStudent(SmsAttendanceReq smsAttendanceReq, String user_id) {

        return null;
    }


}
